<template>
  <div class="h-80 w-80">
    <!-- 添加key强制重新渲染 -->
    <Doughnut v-if="chartData" :key="chartKey" :data="chartData" :options="options" />
    <div v-else class="flex items-center justify-center h-full">
      加载中...
    </div>
  </div>
</template>

<script setup>
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
import { Doughnut } from 'vue-chartjs'
import { ref, onMounted } from "vue";
import { getAllAdmin, getAllStudent, getAllTeacher } from "@/hook/userHook.js";

ChartJS.register(ArcElement, Tooltip, Legend);

// 使用ref创建响应式数据
const chartData = ref(null);
const chartKey = ref(0); // 用于强制重新渲染
const loading = ref(true);

// 配置项
const options = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top',
    },
    tooltip: {
      callbacks: {
        label: function(context) {
          return `${context.label}: ${context.raw}人`;
        }
      }
    }
  }
};

onMounted(async () => {
  try {
    // 并行请求提高效率
    const [students, teachers, admins] = await Promise.all([
      getAllStudent(1, 50, ''),
      getAllTeacher(1, 50, ''),
      getAllAdmin(1, 50, '')
    ]);

    // 创建新对象确保响应式更新
    chartData.value = {
      labels: ['学生', '教师', '管理员'],
      datasets: [{
        backgroundColor: ['#41B883', '#E46651', '#00D8FF'],
        data: [
          students?.records.length || 0,
          teachers?.records.length || 0,
          admins?.records.length || 0
        ]
      }]
    };

    // 强制重新渲染图表
    chartKey.value++;
  } catch (error) {
    console.error('数据加载失败:', error);
    // 设置默认数据
    chartData.value = {
      labels: ['学生', '教师', '管理员'],
      datasets: [{
        backgroundColor: ['#41B883', '#E46651', '#00D8FF'],
        data: [0, 0, 0]
      }]
    };
  } finally {
    loading.value = false;
  }
});
</script>